//
//  RemarkViewController.m
//  Guazi
//
//  Created by koolearn on 11-7-30.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RemarkViewController.h"
#import "Remark.h"
#import "RemarkInputCell.h"
#import "RemarkViewCell.h"
#import "StringUtil.h"
#import "GuaziAppDelegate.h"

@interface RemarkViewController (private) 
- (NSMutableArray*) restoreData;
- (void) loadNewRemarks:(time_t)sinceTime;
- (void) processAfterLoadNewRemarks:(NSObject*)obj;
@end


@implementation RemarkViewController

@synthesize status;


#pragma mark - loadData methods

- (void) loadData 
{
    remarks = [self restoreData];
    [remarks retain];
    
    time_t lastTime = 0;
    if ( [remarks count] > 0 ) {
        Remark* remark = (Remark*) [remarks objectAtIndex:0];
        lastTime = remark.createAt;
    }
    
    /*if ( [remarks count] > 0 ) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    else {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }*/
    
    [self loadNewRemarks:lastTime];
}


- (NSMutableArray*) restoreData
{
    return [Remark loadFromDB:status.statusId rows:200 beforeTime:0];
    return nil;
}


- (void)loadNewRemarks:(time_t)sinceTime
{
    if ( client ) return;
    client = [[TwitterClient alloc] initWithTarget:self action:@selector(didLoadNewRemarks:obj:)];
    [client remarkList:status.statusId sinceTime:sinceTime];
}


- (void) didLoadNewRemarks:(id)sender obj:(NSObject*)obj
{
    client = nil;
    
    [self processAfterLoadNewRemarks:obj];
    
    if ( [remarks count] > 0 ) {
        [self.tableView reloadData];
    }
}


- (void) processAfterLoadNewRemarks:(NSObject*)obj
{
    if ( obj == nil || ![obj isKindOfClass:[NSArray class]] ) return;
    
    Remark* lastRemark = nil;
    if ( [remarks count] > 0 ) {
        lastRemark = [remarks objectAtIndex:0];
    }
    
    NSArray* arr = (NSArray*) obj;
    if ( [arr count] == 0 ) return;
    
    Remark* remark = nil;
    for ( NSDictionary* dic in arr ) {
        remark = [[Remark alloc] initWithJsonDictionary:dic statusId:status.statusId];
        if ( lastRemark ) {
            if ( remark.createAt > lastRemark.createAt ) {
                [remarks insertObject:remark atIndex:0];
            }
        }
        else {
            [remarks insertObject:remark atIndex:0];
        }
    }
    
}


#pragma mark - init & destroy methods

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        remarks = nil;
    }
    return self;
}


- (id) initWithStatus:(Status*)s
{
    self = [super initWithStyle:UITableViewStylePlain];
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    //self.tableView.separatorColor = [UIColor blackColor];
    if ( self ) {
        self.status = s;
        remarks = nil;
    }
    return self;
}


- (void)dealloc
{
    [status release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.0f];
    [self loadData];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.status = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    if (client) {
        [client cancel];
        [client release];
        client = nil;
    }
    [super viewDidDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [remarks count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell1";
    RemarkViewCell* cell = (RemarkViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[RemarkViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    Remark* remark = [remarks objectAtIndex:indexPath.row];
    cell.remark = remark;
    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Remark* remark = [remarks objectAtIndex:indexPath.row];
    CGSize size = [remark.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 600) lineBreakMode:UILineBreakModeCharacterWrap];
    return 30 + size.height;
    //return 25;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

@end
